package org.gaaidou.ptarmigan.springboot.core.common;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public final class AnnotationUtil {
    public static <A extends Annotation> boolean isAnnotation(Method method, Class<A> annotationClass) {
        if (null != method.getDeclaringClass().getAnnotation(annotationClass) || null != method.getAnnotation(annotationClass)) {
            return true;
        } else {
            Method superMethod = getSuperMethod(method);
            if (null != superMethod) {
                return null != superMethod.getDeclaringClass().getAnnotation(annotationClass) || null != superMethod.getAnnotation(annotationClass);
            }
        }
        return false;
    }

    public static <A extends Annotation> boolean isAnnotation(Method method, int paramIndex, Class<A> annotationClass) {
        if (null != method.getParameters()[paramIndex].getAnnotation(annotationClass)) {
            return true;
        } else {
            Method superMethod = getSuperMethod(method);
            if (null != superMethod) {
                return null != superMethod.getParameters()[paramIndex].getAnnotation(annotationClass);
            }
        }
        return false;
    }

    private static Method getSuperMethod(Method method) {
        Class<?>[] interfaces = method.getDeclaringClass().getInterfaces();
        if (interfaces.length > 0) {
            for (Class<?> anInterface : interfaces) {
                try {
                    return anInterface.getMethod(method.getName(), method.getParameterTypes());
                } catch (NoSuchMethodException e) {
                   // nothing to do
                }
            }
        }
        return null;
    }
}
